/**
 * 背景和主题系统演示
 * 展示如何使用背景滚动和主题切换功能
 */

import { ThemeSystem } from './ThemeSystem'

/**
 * 背景系统演示类
 * 提供简单的API来演示背景和主题系统的功能
 */
export class BackgroundDemo {
  private themeSystem: ThemeSystem
  private canvas: HTMLCanvasElement
  private ctx: CanvasRenderingContext2D
  private isRunning: boolean = false
  private animationId: number | null = null
  private lastTime: number = 0

  constructor(canvasId: string) {
    const canvas = document.getElementById(canvasId) as HTMLCanvasElement
    if (!canvas) {
      throw new Error(`Canvas element with id "${canvasId}" not found`)
    }

    this.canvas = canvas
    const context = canvas.getContext('2d')
    if (!context) {
      throw new Error('Failed to get 2D rendering context')
    }

    this.ctx = context
    
    // 设置Canvas尺寸
    this.canvas.width = 800
    this.canvas.height = 400

    // 初始化主题系统
    this.themeSystem = new ThemeSystem({
      canvasWidth: this.canvas.width,
      canvasHeight: this.canvas.height
    })

    // 设置默认主题
    this.setTheme('city')
  }

  /**
   * 开始演示
   */
  start(): void {
    if (this.isRunning) return

    this.isRunning = true
    this.lastTime = performance.now()
    this.gameLoop()
  }

  /**
   * 停止演示
   */
  stop(): void {
    this.isRunning = false
    if (this.animationId !== null) {
      cancelAnimationFrame(this.animationId)
      this.animationId = null
    }
  }

  /**
   * 设置主题
   */
  async setTheme(themeName: string): Promise<void> {
    try {
      await this.themeSystem.setTheme(themeName)
      console.log(`主题已切换到: ${themeName}`)
    } catch (error) {
      console.error('设置主题失败:', error)
    }
  }

  /**
   * 平滑切换主题
   */
  async switchTheme(themeName: string): Promise<void> {
    try {
      await this.themeSystem.switchTheme(themeName, 2000)
      console.log(`主题已平滑切换到: ${themeName}`)
    } catch (error) {
      console.error('切换主题失败:', error)
    }
  }

  /**
   * 设置滚动速度
   */
  setScrollSpeed(speed: number): void {
    this.themeSystem.setScrollSpeed(speed)
    console.log(`滚动速度已设置为: ${speed}`)
  }

  /**
   * 重置背景位置
   */
  resetBackground(): void {
    this.themeSystem.reset()
    console.log('背景位置已重置')
  }

  /**
   * 获取可用主题列表
   */
  getAvailableThemes(): string[] {
    return this.themeSystem.getAvailableThemes().map(theme => theme.name)
  }

  /**
   * 获取当前主题信息
   */
  getCurrentThemeInfo(): { name: string; displayName: string; colors: any } | null {
    const themeData = this.themeSystem.getCurrentThemeData()
    if (!themeData) return null

    return {
      name: themeData.name,
      displayName: themeData.displayName,
      colors: themeData.colors
    }
  }

  /**
   * 游戏循环
   */
  private gameLoop(): void {
    if (!this.isRunning) return

    const currentTime = performance.now()
    const deltaTime = currentTime - this.lastTime
    this.lastTime = currentTime

    // 更新背景系统
    this.themeSystem.update(deltaTime)

    // 渲染
    this.render()

    this.animationId = requestAnimationFrame(() => this.gameLoop())
  }

  /**
   * 渲染场景
   */
  private render(): void {
    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    // 渲染背景
    this.themeSystem.render(this.ctx)

    // 渲染演示信息
    this.renderInfo()
  }

  /**
   * 渲染演示信息
   */
  private renderInfo(): void {
    const themeInfo = this.getCurrentThemeInfo()
    if (!themeInfo) return

    this.ctx.fillStyle = themeInfo.colors.text
    this.ctx.font = '16px Arial'
    this.ctx.fillText(`当前主题: ${themeInfo.displayName}`, 10, 30)
    this.ctx.fillText('按键说明:', 10, 60)
    this.ctx.fillText('1 - 城市主题', 10, 80)
    this.ctx.fillText('2 - 森林主题', 10, 100)
    this.ctx.fillText('3 - 沙漠主题', 10, 120)
    this.ctx.fillText('+ - 加速滚动', 10, 140)
    this.ctx.fillText('- - 减速滚动', 10, 160)
    this.ctx.fillText('R - 重置背景', 10, 180)
  }

  /**
   * 处理键盘输入
   */
  handleKeyPress(event: KeyboardEvent): void {
    switch (event.key) {
      case '1':
        this.switchTheme('city')
        break
      case '2':
        this.switchTheme('forest')
        break
      case '3':
        this.switchTheme('desert')
        break
      case '+':
      case '=':
        this.setScrollSpeed(2.0)
        break
      case '-':
        this.setScrollSpeed(0.5)
        break
      case 'r':
      case 'R':
        this.resetBackground()
        break
    }
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.stop()
    this.themeSystem.cleanup()
  }
}

/**
 * 创建并启动背景演示
 * @param canvasId Canvas元素的ID
 * @returns BackgroundDemo实例
 */
export function createBackgroundDemo(canvasId: string): BackgroundDemo {
  const demo = new BackgroundDemo(canvasId)
  
  // 添加键盘事件监听
  document.addEventListener('keydown', (event) => {
    demo.handleKeyPress(event)
  })

  // 启动演示
  demo.start()

  console.log('背景演示已启动！')
  console.log('可用主题:', demo.getAvailableThemes())
  console.log('使用数字键1-3切换主题，+/-调整滚动速度，R重置背景')

  return demo
}